package com.ruoyi.resume.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.resume.domain.model.resumeProfile.EducationBackground;
import com.ruoyi.resume.domain.model.MajorCategory;
import com.ruoyi.resume.domain.model.SchoolCategory;
import com.ruoyi.resume.domain.model.Tag;
import com.ruoyi.resume.domain.request.LabelingRequest;
import com.ruoyi.resume.exception.InvalidParameterException;
import com.ruoyi.resume.service.EducationBackgroundLabelingService;
import com.ruoyi.resume.utils.LabelingUtils;
import lombok.Cleanup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class EducationBackgroundLabelingServiceImpl implements EducationBackgroundLabelingService {

    private SchoolCategory schoolCategory;
    private MajorCategory majorCategory;

    @Autowired
    private LabelingUtils labelingUtils;

    // 构造器加载学校类别信息
    public EducationBackgroundLabelingServiceImpl() {
        try {
            // 加载学校类别信息
            ClassPathResource schoolResource = new ClassPathResource("schools.json");
            @Cleanup
            InputStream schoolInputStream = schoolResource.getInputStream();
            ObjectMapper objectMapper = new ObjectMapper();
            schoolCategory = objectMapper.readValue(schoolInputStream, SchoolCategory.class);

            // 加载专业类别信息
            ClassPathResource majorResource = new ClassPathResource("majors.json");
            @Cleanup
            InputStream majorInputStream = majorResource.getInputStream();
            majorCategory = objectMapper.readValue(majorInputStream, MajorCategory.class);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Map<String, Integer>> processSchoolTypeRequest(LabelingRequest request) {
        validateRequest(request);

        // 原有逻辑：提取学校名称
        List<String> schoolNames = request.getSplitResumeResult().getEducationBackgrounds().stream()
                .map(EducationBackground::getSchoolName)
                .collect(Collectors.toList());

        if (schoolNames.isEmpty()) {
            throw new InvalidParameterException("学校信息缺失");
        }

        // 保留原有的学校类别标签逻辑
        Set<String> labels = new HashSet<>();
        for (String schoolName : schoolNames) {
            if (schoolName != null) {
                boolean is985 = schoolCategory.getIs985() != null && schoolCategory.getIs985().contains(schoolName);
                boolean is211 = schoolCategory.getIs211() != null && schoolCategory.getIs211().contains(schoolName);

                if (is985) {
                    labels.add("985");
                    labels.add("211");
                } else if (is211) {
                    labels.add("211");
                }
            }
        }

        // 将生成的标签映射到标签列表
        return mapLabelsToTags(labels, labelingUtils.getTagsByCategoryId(request.getCategory().getId()));
    }

    @Override
    public List<Map<String, Integer>> processMajorTypeRequest(LabelingRequest request) {
        validateRequest(request);

        // 原有逻辑：提取专业名称
        List<String> majorNames = request.getSplitResumeResult().getEducationBackgrounds().stream()
                .map(EducationBackground::getMajorName)
                .collect(Collectors.toList());

        if (majorNames.isEmpty()) {
            throw new InvalidParameterException("专业信息缺失");
        }

        // 保留原有的专业类别标签逻辑
        List<String> labels = new ArrayList<>();
        if (majorCategory.getMajorCategories() != null) {
            for (String majorName : majorNames) {
                if (majorName != null) {
                    for (Map.Entry<String, List<String>> entry : majorCategory.getMajorCategories().entrySet()) {
                        String category = entry.getKey();
                        List<String> majors = entry.getValue();

                        if (majors != null && majors.contains(majorName)) {
                            labels.add(category);
                            break;
                        }
                    }
                }
            }
        }

        // 将生成的标签映射到标签列表
        return mapLabelsToTags(labels, labelingUtils.getTagsByCategoryId(request.getCategory().getId()));
    }

    @Override
    public List<Map<String, Integer>> processGraduatedRequest(LabelingRequest request) {
        validateRequest(request);

        List<YearMonth> endTimeList = request.getSplitResumeResult().getEducationBackgrounds().stream()
                .map(EducationBackground::getEndTime)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        if (endTimeList.isEmpty()) {
            throw new InvalidParameterException("毕业时间信息缺失");
        }

        // 获取最靠后的毕业时间
        YearMonth latestEndTime = endTimeList.stream()
                .max(YearMonth::compareTo)
                .orElseThrow(() -> new InvalidParameterException("无法获取有效的毕业时间"));

        String label = latestEndTime.getYear() >= YearMonth.now().getYear() ? "应届生" : "社会生";
        return mapLabelsToTags(Collections.singletonList(label), labelingUtils.getTagsByCategoryId(request.getCategory().getId()));
    }

    @Override
    public List<Map<String, Integer>> processHighestDegreeRequest(LabelingRequest request) {
        validateRequest(request);

        List<String> degrees = request.getSplitResumeResult().getEducationBackgrounds().stream()
                .map(EducationBackground::getDegree)
                .collect(Collectors.toList());

        if (degrees.isEmpty()) {
            throw new InvalidParameterException("学历信息缺失");
        }

        String highestDegree = findHighestDegree(degrees);
        return mapLabelsToTags(Collections.singletonList(highestDegree), labelingUtils.getTagsByCategoryId(request.getCategory().getId()));
    }

    private void validateRequest(LabelingRequest request) {
        if (request.getSplitResumeResult() == null ||
                request.getSplitResumeResult().getEducationBackgrounds() == null ||
                request.getSplitResumeResult().getEducationBackgrounds().isEmpty()) {
            throw new InvalidParameterException("教育背景信息缺失");
        }
    }

    private String findHighestDegree(List<String> degrees) {
        List<String> validDegrees = Arrays.asList("博士", "硕士", "本科", "大专", "高中", "中专", "初中", "小学");
        return degrees.stream()
                .filter(validDegrees::contains)
                .max(Comparator.comparingInt(validDegrees::indexOf))
                .orElseThrow(() -> new InvalidParameterException("学历信息无效"));
    }

    private List<Map<String, Integer>> mapLabelsToTags(Collection<String> labels, List<Tag> tags) {
        List<Map<String, Integer>> result = new ArrayList<>();
        for (String label : labels) {
            for (Tag tag : tags) {
                if (label.equals(tag.getTagValue())) {
                    Map<String, Integer> map = new HashMap<>();
                    map.put(label, tag.getId());
                    result.add(map);
                }
            }
        }
        return result;
    }
}
